package com.ytjj.qmyx.mall.controller;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.qmyx.mall.constants.ExpireTimeConstant;
import com.ytjj.qmyx.mall.constants.ProductRecordConstant;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.model.request.AddShopCartRequest;
import com.ytjj.qmyx.mall.model.request.DelShopCartRequest;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.ProductService;
import com.ytjj.qmyx.mall.utils.ProductRecordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车
 *
 *
 * @version 1.0
 * 
 */
@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController extends BaseController {

    private final RedisService redisService;

    private final ProductService productService;

    private final ActivityService activityService;

    @Resource
    private ProductRecordUtil productRecordUtil;

    public CartController(RedisService redisService, ProductService productService,ActivityService activityService) {
        this.redisService = redisService;
        this.productService = productService;
        this.activityService = activityService;
    }

    /**
     * 添加购物车
     *
     * @return
     */
    @PostMapping("/addShoppingCart")
    public CommonResult addShoppingCart(@RequestBody AddShopCartRequest shopCartRequest) {
        UsersResponse usersResponse = this.getCurrentUser();
        ProductSpecResponse spec = productService.getProductSpecInfoById(shopCartRequest.getProductSpecId());
        if(spec.getPrice().doubleValue() == 0D || spec.getCurPrice().doubleValue() == 0d) {
            return CommonResult.success(ResultCode.SUCCESS);
        }
        ProductResponse product = productService.getProductById(shopCartRequest.getProductId(),shopCartRequest.getModular());
        if(product.getPrice().doubleValue() == 0D || product.getCurPrice().doubleValue() == 0d) {
            return CommonResult.success(ResultCode.SUCCESS);
        }
        CartProductResponse cartResponse = new CartProductResponse(product, spec,shopCartRequest.getProductSum());
        redisService.add(RedisConstants.CART_KEY_V2 + usersResponse.getId(), OrderUtils.getCartCode(shopCartRequest.getProductSpecId()), JSONObject.toJSONString(cartResponse));
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 添加购物车(v2)
     *
     * @return
     */
    @PostMapping("/addShoppingCartV2")
    public CommonResult addShoppingCartV2(@RequestBody AddShopCartRequest shopCartRequest) {
        UsersResponse usersResponse = this.getCurrentUser();
        // 普通商品
        ProductSpecResponse spec = productService.getProductSpecInfoById(shopCartRequest.getProductSpecId());
        if(spec.getPrice().doubleValue() == 0D || spec.getCurPrice().doubleValue() == 0d) {
            return CommonResult.success(ResultCode.SUCCESS);
        }
        ProductResponse product = productService.getProductById(shopCartRequest.getProductId(),shopCartRequest.getModular());
        if(product.getPrice().doubleValue() == 0D || product.getCurPrice().doubleValue() == 0d) {
            return CommonResult.success(ResultCode.SUCCESS);
        }
        CartProductResponse cartResponse = new CartProductResponse(product, spec,shopCartRequest.getProductSum());
        // 是否直接购买
        cartResponse.setIsDirectBuy(shopCartRequest.getIsDirectBuy());
        redisService.add(RedisConstants.CART_KEY_V2 + usersResponse.getId(), OrderUtils.getCartCode(shopCartRequest.getProductSpecId()), JSONObject.toJSONString(cartResponse));
        redisService.expire(RedisConstants.CART_KEY_V2 + usersResponse.getId(), ExpireTimeConstant.EXPIRE_SECONDS);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 获取购物车列表
     *
     * @return
     */
    @PostMapping("/getShoppingCart")
    public CommonResult getShoppingCart() {
        UsersResponse usersResponse = this.getH5CurrentUser();
        List<CartProductResponse> cartResponseList = new ArrayList<>();
        if(usersResponse == null){
            // 前端要求给空数组
            return CommonResult.success(cartResponseList);
        }
        Map<Object, Object> map = redisService.getHashEntries(RedisConstants.CART_KEY_V2 + usersResponse.getId());
        map.forEach((key, value) -> {
            String json = (String) value;
            CartProductResponse cartResponse = JSONObject.parseObject(json, CartProductResponse.class);
            cartResponse.setPrice(cartResponse.getSpecPrice());
            cartResponse.setCartNo((String) key);
            cartResponse.setProductSum(cartResponse.getProductSum());
            cartResponseList.add(cartResponse);
        });
        return CommonResult.success(cartResponseList.stream()
                .sorted(Comparator.comparing(CartProductResponse::getCartNo,(c1,c2)-> c2.compareTo(c1)))
                .collect(Collectors.toList()));
    }

    /**
     * 删除购物车
     *
     * @param cartRequest
     * @return
     */
    @PostMapping("/delShoppingCart")
    public CommonResult delShoppingCart(@RequestBody DelShopCartRequest cartRequest){
        UsersResponse usersResponse = this.getCurrentUser();
        redisService.delete(RedisConstants.CART_KEY_V2 + usersResponse.getId(),cartRequest.getCartNos());
        return CommonResult.success(ResultCode.SUCCESS);
    }
}
